package de.homer.server.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import de.homer.core.user.domain.User;
import de.homer.persistence.exceptions.UserNotFoundException;
import de.homer.persistence.user.UserRepository;

/**
 * A service checking the login data.
 * 
 * @author André Stannek
 * 
 */
@Service("loginService")
public class LoginService implements Serializable, UserDetailsService {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3932821539142894572L;

	/**
	 * 
	 */
	@Autowired
	private UserRepository userRepository;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.security.core.userdetails.UserDetailsService#
	 * loadUserByUsername(java.lang.String)
	 */
	@Override
	public final UserDetails loadUserByUsername(final String username) {
		try {
			User user = userRepository.getUser(username);
			return new org.springframework.security.core.userdetails.User(
					user.getUsername(), user.getPassword(), true, true, true,
					true, getAuthorities(user));
		} catch (UserNotFoundException e) {
			throw new UsernameNotFoundException(e.getMessage(), e);
		}
	}

	/**
	 * 
	 * @param user
	 *            The {@link User} to get the {@link GrantedAuthority}s for
	 * @return the {@link GrantedAuthority}s of the given {@link User}
	 */
	private Collection<GrantedAuthority> getAuthorities(final User user) {
		List<GrantedAuthority> authList = new ArrayList<>(2);
		authList.add(new SimpleGrantedAuthority("ROLE_USER"));
		authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
		return authList;
	}
}
